package com.zsrt.devbase.common.utils;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class WebUtil {
	
	public static ResponseEntity<Map<String, Object>> getResponseEntity(Map<String, Object> obj) {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		
		return new ResponseEntity<Map<String, Object>>(obj, headers, HttpStatus.OK);
	}
	
	
	
	/**
	 * 获取session对象
	 * @return
	 */
	public static HttpSession getSession() {
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
		if (request == null) {
			return null;
		}
		HttpSession session = request.getSession(false);
		if (session == null) {
			throw new RuntimeException("session已失效！");
		}
		return session;
	}
	
	/**
	 * 根据key获取session
	 * 
	 * @param key
	 * @return
	 */
	public static Object getSession(String key) {
		HttpSession session = getSession();
		Object obj = null;
		if (!StringUtils.isEmpty(key)) {
			obj = session.getAttribute(key);
		}
		return obj;
	}
	/**
	 * @Description: 绑定数据至session中
	 * @MethodName: setSeesion
	 * @param key
	 * @param value void 返回类型
	 */
	public static void setSeesion(String key,String value){
		HttpSession session = getSession();
		if (!StringUtils.isEmpty(key)&&!StringUtils.isEmpty(value)) {
			session.setAttribute(key, value);
		}
	}
}
